package com.jason.auto.controller;

import com.jason.auto.common.BizException;
import com.jason.auto.common.ResultCode;
import com.jason.auto.model.User;
import com.jason.auto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
public class PageController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String toIndex() {
        return "index";
    }

    @GetMapping("page/console")
    public String toConsole() {
        return "console";
    }

    @GetMapping("page/user/list")
    public String toUserList() {
        return "user/user/list";
    }

    @GetMapping(value = {"page/user/edit/{userId}", "page/user/add"})
    public ModelAndView toEditUser(@PathVariable(required = false) Long userId,
                                   ModelAndView modelAndView) {
        modelAndView.setViewName("user/user/userform");
        if (Objects.isNull(userId)) {
            return modelAndView;
        }
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new BizException(ResultCode.USER_NOT_FOUND);
        }
        modelAndView.addObject("userId", user.getId());
        modelAndView.addObject("name", user.getName());
        modelAndView.addObject("phone", user.getPhone());
        modelAndView.addObject("roleId", user.getRoleId());

        List<User> userList = new ArrayList<>();
        userList.add(user);
        userList.add(user);
        modelAndView.addObject("role-list", userList);
        return modelAndView;
    }

    @RequestMapping("page/menu1")
    public String toMenu1() {
        return "temp/menu1";
    }

    @RequestMapping("page/menu2")
    public String toMenu2() {
        return "temp/menu2";
    }

    @RequestMapping("page/user")
    public String toUser() {
        return "user/list";
    }

}
